package com.yc.javaee.网络编程;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.Buffer;
import java.util.Scanner;

public class Server {

    public static void main(String[] args) throws IOException, InterruptedException {

        ServerSocket server = new ServerSocket(8888);
        System.out.println("服务器创建成功, 等待连接, 端口 8888 :");
        Socket socket = server.accept();// IO 操作 ==> 阻塞

        // 我的地址
        InetAddress inetAddress = socket.getInetAddress();
        System.out.println(inetAddress);
        // 对方地址
        SocketAddress remoteAddress = socket.getRemoteSocketAddress();
        System.out.println(remoteAddress);

        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();
        Scanner sc = new Scanner(System.in);

        byte[] buffer =  new byte[1024];
        boolean running = true;

        // 读的线程
        Thread t1 = new Thread(()->{
            int count;
            while(running){
                try {
                    count = in.read(buffer);     // 阻塞
                    System.out.println("客户端说:" + new String(buffer,0,count));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();

        // 写的线程
        Thread t2 = new Thread(()->{
            while(running){
                System.out.println("我说: ");
                String msg = sc.nextLine();  // 阻塞
                try {
                    out.write(msg.getBytes());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t2.start();

        t1.join();
        t2.join();
        // 如果让 socket 在 对话结束后关闭
        socket.close();

    }

}
